import { useState } from 'react'
import { storage } from '@/services/storage'
import { calculateNextInterval, getDueCards } from '@/utils/studyUtils'

export const useStudySession = (refreshStats) => {
  const [currentCard, setCurrentCard] = useState(null)
  const [showAnswer, setShowAnswer] = useState(false)
  const [selectedDeckId, setSelectedDeckId] = useState('')
  const [remainingCards, setRemainingCards] = useState([])

  const handleAnswer = (quality) => {
    if (!currentCard) return

    const { interval, easeFactor } = calculateNextInterval(currentCard, quality)
    const nextReview = new Date()
    nextReview.setDate(nextReview.getDate() + interval)

    const updatedCard = {
      ...currentCard,
      interval,
      easeFactor,
      nextReview,
      reviews: (currentCard.reviews || 0) + 1,
      correct: (currentCard.correct || 0) + (quality >= 3 ? 1 : 0),
      incorrect: (currentCard.incorrect || 0) + (quality < 3 ? 1 : 0),
      modified: new Date()
    }

    storage.saveCard(updatedCard)
    
    const newRemainingCards = remainingCards.slice(1)
    setRemainingCards(newRemainingCards)
    setCurrentCard(newRemainingCards[0] || null)
    setShowAnswer(false)
  }

  const startStudy = (deckId) => {
    const cards = storage.getCardsByDeck(deckId)
    const dueCards = getDueCards(cards)
    setRemainingCards(dueCards)
    setSelectedDeckId(deckId)
    if (dueCards.length > 0) {
      setCurrentCard(dueCards[0])
      setShowAnswer(false)
    }
  }

  const endStudy = () => {
    setSelectedDeckId('')
    setCurrentCard(null)
    setShowAnswer(false)
    setRemainingCards([])
    refreshStats()
  }

  return {
    currentCard,
    showAnswer,
    selectedDeckId,
    remainingCards,
    setShowAnswer,
    handleAnswer,
    startStudy,
    endStudy
  }
}